package net.thxjj.mobileServer.filter;

import io.jsonwebtoken.ExpiredJwtException;
import net.thxjj.mobileServer.entity.GenieResum;
import net.thxjj.mobileServer.service.IUserService;
import net.thxjj.mobileServer.util.JwtUtil;
import net.thxjj.mobileServer.util.ParameterMap;
import net.thxjj.mobileServer.util.Tools;
import net.thxjj.sitermodel.MobileUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录拦截
 * @author rstyro
 *
 */
@WebFilter(filterName="loginFilter",urlPatterns={"/*"})
public class LoginFilter implements Filter{
	Logger logger = LoggerFactory.getLogger(getClass());

	//不过滤的地址
	private static final String NOT_FILTER="/((device)|(genie)|(alexa)|(uaa)|(login)|(refreshToken)|(sendWebsocket)|(Test)).*";

	//静态资源文件地址
	private static final String PTAH_REG=".*\\.((js)|(css)|(png)|(jpg)|(woff)|(woff2)|(map)|(svg)|(ttf)|(ico)|(json)|(gif))";

	@Autowired
	private IUserService iUserService;

    @Override
    public void destroy() {}
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
    	 HttpServletRequest request = (HttpServletRequest) req;
         HttpServletResponse response = (HttpServletResponse) res;
         String path = request.getServletPath();
         if(!path.matches(PTAH_REG) && !path.matches(NOT_FILTER)){
				 if(SelfChekToken(request))
				        chain.doFilter(request, response);
				 else{
						response.sendError(401);
				 }
				 return;
         }
    	
        chain.doFilter(request, response);
    }
    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

	private boolean SelfChekToken(HttpServletRequest request){


		String token = request.getHeader("Authorization");
		if(Tools.isEmpty(token)){
			return false;
		}else{
			if(token.startsWith("Bearer ")){
				token =token.substring(7);

				try {
					MobileUser u = JwtUtil.parse(token);
					System.out.println(u);
					MobileUser myUser = iUserService.getUserInfoById(u.getUserId());
					if(myUser!=null&&myUser.getUserId()>0){
						request.getSession().setAttribute("user_id",myUser.getUserId());
						return true;
					}else{
						return false;
					}
				}catch (Exception e){
					e.printStackTrace();
					return false;
				}
			}else{
				return false;
			}
		}

	}

}
